import axios from "axios";
import { refreshToken } from "./userApi";
import { useUserStore } from "@/stores/user";
import { ElMessage } from 'element-plus'
const instance = axios.create(({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 6000
}))
instance.interceptors.request.use(async function (config) {
  const store = useUserStore()
  if (/login|register|refreshToken/.test(config.url)) return config
  await refreshToken()
  if (store.accessToken) {
    config.headers.Authorization = store.accessToken
  }
  return config
}, function (error) {
  return Promise.reject(error)
})
instance.interceptors.response.use(function (response) {
  const store = useUserStore()
  if (response.data.code === 10000) {
    if (response.data.data && response.data.data.accessToken) {
      store.accessToken = response.data.data.accessToken
      store.accessTokenTime = Date.now()
    }
    if (response.data.data && response.data.data.refreshToken) {
      store.refreshToken = response.data.data.refreshToken
    }
    if (response.data.data && response.data.data.userInfo) {
      store.userInfo = response.data.data.userInfo
    }
  }
  ElMessage({
    message: response.data.message,
    type: ["info", "success", "warning", "error", "error", "error"][Math.floor(response.status / 100) - 1],
  })
  return response
}, function (error) {
  ElMessage({
    message: error.message,
    type: ["info", "success", "warning", "error", "error", "error"][Math.floor(error.status / 100) - 1],
  })
  return Promise.reject(error)
})
export default instance
